if (!myApp) {
  var myApp = angular.module("myApp", ['treeControl']);
}

var Groups = {
  '*': {
    text: '所有',
    type: '*'
  }
};

var nowGroup = null;

//当前告警控制器
myApp.controller("behCtrl", function ($scope, $location, $rootScope, $http, $filter) {
  let listTimer = null;
  let autoplay = false;
  $scope.Groups = Groups;
  $scope.pages = {
    data: [],
    count: 0,
    maxPage: "...",
    pageNow: 1
  };

  $scope.IDList = [];
  $scope.ItemList = {};

  $scope.select_model = [{
    num: '10',
    type: "10条/页"
  },
  {
    num: '20',
    type: "20条/页"
  },
  {
    num: '50',
    type: "50条/页"
  },
  {
    num: '100',
    type: "100条/页"
  },
  ]
  $scope.select = {
    model: '10'
  }

  //告警事件
  $scope.AlertType_select = [{
    label: "可疑行为",
    num: 4
  },
  {
    label: "可疑文件",
    num: 1
  },
  {
    label: "可疑IP",
    num: 2
  },
  {
    label: "可疑URL",
    num: 3
  },
  {
    css: "danger",
    label: "漏洞利用",
    num: 6
  },
  {
    label: "勒索软件",
    num: 7
  },
  {
    label: "所有",
    num: 10
  }
  ];
  //批量选取数据
  $scope.IDListData = [];
  console.log(localStorage.getItem("NowPage"));
  if (localStorage.getItem("NowPage") == 'detail' && localStorage.getItem("aletSearch")) {
    var searchDataList = JSON.parse(localStorage.getItem("aletSearch"))
    var pageRows = JSON.parse(localStorage.getItem("pageRows"))
    var pageNow = JSON.parse(localStorage.getItem("page"))
    //设置默认参数
    $scope.searchData = {
      startTime: searchDataList.startTime,
      endTime: searchDataList.endTime,
      ComputerName: searchDataList.ComputerName,
      AlertType: searchDataList.AlertType * 1,
      Label: searchDataList.Label,
      sid: searchDataList.sid,
      gid: searchDataList.gid,
      MinPoint: searchDataList.MinPoint,
      MaxPoint: searchDataList.MaxPoint
    };
    console.log(99999999);
    console.log(pageRows);

    setTimeout(function () {
      $scope.$apply(function () {
        $scope.select.model = pageRows
      });
    }, 200);
    $scope.pages.pageNow = pageNow
  } else {
    //设置默认参数
    $scope.searchData = {
      startTime: moment()
        .subtract(365, "days")
        .unix(),
      endTime: moment().unix(),
      ComputerName: "",
      AlertType: 10,
      Label: "",
      gid: "",
      sid: "",
      MinPoint: 0,
      MaxPoint: 100
    };
  }
  setTimeout(function () {
    $scope.$apply(function () {
      $scope.select.model = '10'
    });
  }, 200);
  if (location.search) {
    var ComputerName = localStorage.getItem("parmas");
    var SensorID = localStorage.getItem("SensorID");
    // $scope.searchData.ComputerName = ComputerName;
    $scope.searchData.sid = SensorID;
  }
  //告警组下拉框
  $scope.alertGid_select = GroupList;

  $scope.AlertType_str = [{
    css: "warning",
    label: "可疑行为",
    num: 0
  },
  {
    css: "danger",
    label: "可疑文件",
    num: 1
  },
  {
    css: "danger",
    label: "可疑IP",
    num: 2
  },
  {
    css: "danger",
    label: "可疑URL",
    num: 3
  },
  {
    css: "warning",
    label: "可疑行为",
    num: 4
  },
  {
    css: "warning",
    label: "可疑行为",
    num: 5
  },
  {
    css: "danger",
    label: "漏洞利用",
    num: 6
  },
  {
    css: "danger",
    label: "勒索软件",
    num: 7
  }
  ];

  $scope.status_str = [{
    css: "success",
    label: "新告警"
  },
  {
    css: "danger",
    label: "未解决"
  },
  {
    css: "default",
    label: "已解决"
  },
  {
    css: "primary",
    label: "白名单"
  },
  {
    css: "primary",
    label: "例外"
  }
  ];

  $scope.OldType_str = {
    IP: {
      label: "可疑IP",
      css: "warning"
    },
    URL: {
      label: "可疑URL",
      css: "warning"
    },
    Beh: {
      label: "可疑行为",
      css: "warning"
    },
    File: {
      label: "可疑文件",
      css: "danger"
    },
    Loophole: {
      label: "漏洞利用",
      css: "danger"
    },
    extortion: {
      css: "danger",
      label: "勒索软件"
    }
  };

  //警告列表跳转
  $scope.detail = function (item, $event) {
    if ($event.target.nodeName == "BUTTON") {
      return;
    } else {
      localStorage.setItem("aletSearch", JSON.stringify($scope.searchData));
      localStorage.setItem("pageRows", JSON.stringify($scope.select.model));
      localStorage.setItem("page", JSON.stringify($scope.pages.pageNow));
      localStorage.setItem("NowPage", 'detail')
      switch (item.Type) {
        case "File":
          location.href = "file?id=" + item.rid;
          break;
        case "IP":
          location.href = "ip?id=" + item.rid;
          break;
        case "URL":
          location.href = "url?id=" + item.rid;
          break;
        case "Beh":
          if (item.AlertType == 6) {
            location.href = "loophole?id=" + item.rid;
          } else {
            location.href = "beh?id=" + item.rid;
          }
          break;
        case "Ransom":
          if (item.AlertType == 7) {
            location.href = "extortion?id=" + item.rid;
          }
          break;
      }
    }
  };

  function IDValidate (callback) {
    if ($scope.IDList.length == 0) {
      zeroModal.error({
        content: "操作失败",
        contentDetail: "请选择计算机！"
      });
      return;
    }
    callback();
  }

  //获取告警数据列表数据
  $scope.getnewPage = function (pageNow) {
    $scope.IDList = [];
    $scope.IDListData = [];
    $scope.searchObj = $scope.searchData;
    pageNow = pageNow ? pageNow : $scope.pages.pageNow;
    console.log($scope.searchObj);
    var params = {
      stime: $scope.searchObj.startTime,
      etime: $scope.searchObj.endTime,
      ComputerName: $scope.searchObj.ComputerName,
      AlertType: $scope.searchObj.AlertType,
      Label: $scope.searchObj.Label,
      MinPoint: $scope.searchObj.MinPoint,
      sid: $scope.searchObj.sid ? $scope.searchObj.sid : '',
      MaxPoint: $scope.searchObj.MaxPoint,
      page: pageNow,
      rows: $scope.select.model,
      gid: $scope.searchObj.gid
    };
    if (!autoplay) {
      params.stime = '';
      params.etime = '';
    }
    $scope.pageGeting = true;
    $http.post("newpage", params).then(
      function success (rsp) {
        $scope.pageGeting = false;
        $scope.pages = rsp.data;
        angular.forEach($scope.pages.data, function (item) {
          $scope.labelArry = item.Label.split("\\");
          item.Label = $scope.labelArry[$scope.labelArry.length - 1];
        });
        $scope.ItemList = $scope.pages.data;
      },
      function err (rsp) {
        $scope.pageGeting = false;
      }
    );
  };

  $scope.getnewPage();

  // 选择页面数据条数,更新数据
  $scope.select_change = function () {
    $scope.getnewPage();
  }


  //搜索按钮点击事件
  $scope.search = function () {
    clearInterval(listTimer);
    autoplay = true;
    $scope.searchNew = JSON.stringify($scope.searchData);
    $scope.getnewPage();
    localStorage.setItem("NowPage", "alert");
  };

  $scope.getChart = function () {
    $http.post("chart-data", {}).then(
      function success (rsp) {
        updateChart(rsp.data);
      },
      function err (rsp) { }
    );
  };

  function updateChart (data) {
    if (data.chartData) {
      if (data.chartData.AlertSensor && updateSensorChart != null) {
        updateSensorChart(data.chartData.AlertSensor);
      }
      if (data.chartData.AlertSrcType && updateAlertChart != null) {
        updateAlertChart(data.chartData.AlertSrcType);
      }
    }
  }

  $scope.setAriaID = function (item, $event) {
    $event.stopPropagation();
    if ($scope.ariaID == item.id) {
      $scope.ariaID = null;
    } else {
      $scope.ariaID = item.id;
    }
  };

  $scope.delAriaID = function ($event) {
    $event.stopPropagation();
    setTimeout(function () {
      $scope.ariaID = null;
    }, 10);
  };

  $scope.update = function (type, item) {
    var rqs_data = {
      type: type,
      List: []
    };
    // 已解决
    if (type == "setOld") { }
    var send = function () {
      var loading = zeroModal.loading(4);
      $http.post("update", rqs_data).then(
        function success (rsp) {
          $scope.getnewPage();
          zeroModal.close(loading);
        },
        function err (rsp) {
          zeroModal.close(loading);
        }
      );
    };

    let flag = Object.prototype.toString.call(item);

    if (flag === '[object Object]') {
      rqs_data.List.push(item);
      send();
    } else if (flag === '[object Array]') {
      rqs_data = {
        type: type,
        List: item
      };
      $scope.IDList = [];
      $scope.IDListData = [];
      send();
    } else {
      IDValidate(function () {
        for (var i = $scope.IDList.length - 1; i >= 0; i--) {
          rqs_data.List.push($scope.ItemList[$scope.IDList[i]]);
        }
        send();
      });
    }
  };

  $scope.getChart();

  listTimer = setInterval(function () {
    //$scope.searchData.startTime = moment().subtract(365, 'days').unix();
    //$scope.searchData.endTime = moment().unix();
    $scope.getnewPage();
  }, 5000);

  setInterval(function () {
    $scope.getChart();
  }, 10000);
  // setInterval(function () {
  //     $scope.searchData.startTime = moment().subtract(365, 'days').unix();
  //     $scope.searchData.endTime = moment().unix();
  //     $scope.timepicker();
  //     $scope.getnewPage($scope.pages.pageNow);
  // }, 5000);
  // 时间插件初始化
  $scope.timepicker = function (params) {
    $(".timerange").daterangepicker({
      timePicker: true,
      // timePickerIncrement: 10,
      // startDate: moment().subtract(365, "days"),
      startDate: moment($scope.searchData.startTime * 1000),
      // endDate: moment($scope.searchData.endTime),
      endDate: moment($scope.searchData.endTime * 1000),
      locale: {
        applyLabel: "确定",
        cancelLabel: "取消",
        format: "YYYY-MM-DD HH:mm",
        customRangeLabel: "指定时间范围"
      },
      ranges: {
        今天: [moment().startOf("day"), moment().endOf("day")],
        "7日内": [
          moment()
            .startOf("day")
            .subtract(7, "days"),
          moment().endOf("day")
        ],
        本月: [moment().startOf("month"), moment().endOf("day")],
        今年: [moment().startOf("year"), moment().endOf("day")]
      }
    },
      function (start, end, label) {
        $scope.searchData.startTime = start.unix();
        $scope.searchData.endTime = end.unix();
      }
    );
  };
  $scope.timepicker();
  $scope.myKeyup_min = function (item) {
    if (item < 0) {
      $scope.searchData.MinPoint = 0;
    } else if (item > 100) {
      $scope.searchData.MinPoint = 100;
    }
  };
  $scope.myKeyup_max = function (item) {
    if (item < 0) {
      $scope.searchData.MaxPoint = 0;
    } else if (item > 100) {
      $scope.searchData.MaxPoint = 100;
    }
  };

  //计算机名点击链接计算机卡片
  $scope.linkToSensor = function (SensorID, $event) {
    $event.stopPropagation();
    location.href = "/sensor/detail?sid=" + SensorID;
  }

  //当前告警checkbox单选
  $scope.selectOne = function (item, $event) {
    $event.stopPropagation();
    //停掉自动刷新状态
    clearInterval(listTimer);
    var index = $scope.IDList.indexOf(item.id);

    if (index == -1) {
      $scope.IDList.push(item.id);
      $scope.IDListData.push(item);
    } else {
      $scope.IDList.splice(index, 1);
      $scope.IDListData.splice(index, 1);
    }
  }

  //当前告警checkbox全选
  $scope.selectAll = function () {
    //停掉自动刷新状态
    clearInterval(listTimer);
    if ($scope.IDList.length === $scope.pages.data.length) {
      $scope.IDList = [];
      $scope.IDListData = [];
    } else {
      $scope.IDList = [];
      $scope.IDListData = [];
      for (var i in $scope.pages.data) {
        var data = $scope.pages.data[i];
        $scope.IDList.push(data.id);
        $scope.IDListData.push(data);
      }
    }
  }

  //批量处理取消点击事件
  $scope.celAlert = function () {
    $scope.IDList = [];
    $scope.IDListData = [];
  }
  $scope.treeOptions = {
    nodeChildren: "child",
    dirSelectable: true,
    allowDeselect: false,
    injectClasses: {
      ul: "a1",
      li: "a2",
      liSelected: "a7",
      iExpanded: "a3",
      iCollapsed: "a4",
      iLeaf: "a5",
      label: "a6",
      labelSelected: "a8"
    }
  }
  $scope.dataForTheTree = [];
  $scope.grounpSelectInput = '所有'
  $scope.groupText = '所有'
  //告警组点击事件
  $scope.searchGroups = function () {
    $scope.getGroupTree()
    $scope.searchGroupTreeInput = ''
    var W = 480;
    var H = 360;
    $scope.option = 'hide';
    // $scope.$apply();
    zeroModal.show({
      title: '请选择计算机分组！',
      content: groupTree,
      width: W + "px",
      height: H + "px",
      ok: true,
      cancel: true,
      okFn: function () {
        $scope.$apply(function (params) {
          $scope.grounpSelectInput = $scope.grounpSelect.text
        })
        if ($scope.grounpSelectInput == '全部') {
          // zeroModal.error('请选择计算机分组！');
          $scope.searchData.gid = '';
          hide_box.appendChild(groupTree);
          $scope.$apply();
          zeroModal.closeAll();
          return false;
        }
        $scope.searchData.gid = $scope.grounpSelect.id;
        //$scope.searchDataChange('group');
        $scope.groupText = $scope.grounpSelect.text;
      },
      onCleanup: function () {
        hide_box.appendChild(groupTree);
        $scope.option = 'show';
      }
    });
  }
  $scope.showSelected = function (node, selected) {
    $scope.grounpSelect = node
  }
  $scope.getGroupTree = function () {
    $http.get('/group/tree').then(function success (rsp) {
      let arr = [
        {
          id: 0,
          text: '所有',
          child: rsp.data.data
        }
      ]
      $scope.oldDataForTheTree = arr
      $scope.dataForTheTree = arr
    }, function err (rsp) {
    });
  }
  $scope.getGroupTree()
  $scope.searchGroupTree = function () {
    let newdataForTheTree = JSON.parse(JSON.stringify($scope.oldDataForTheTree))
    let arr = []
    $scope.treeTArr(newdataForTheTree).map(function (item) {
      if (item.text.search($scope.searchGroupTreeInput) != -1) {
        arr.push(item)
      }
    })
    $scope.dataForTheTree = $scope.ArrToTree(arr)
  }

  // 树形结构数据转单层数组形式
  $scope.treeTArr = function (nodes) {
    var r = [];
    if (Array.isArray(nodes)) {
      for (var i = 0, l = nodes.length; i < l; i++) {
        r.push(nodes[i]); // 取每项数据放入一个新数组
        if (Array.isArray(nodes[i]["child"]) && nodes[i]["child"].length > 0)
          // 若存在children则递归调用，把数据拼接到新数组中，并且删除该children
          r = r.concat($scope.treeTArr(nodes[i]["child"]));
        delete nodes[i]["child"]
      }
    }
    return r;

  }

  $scope.ArrToTree = function (treeArray) {
    var r = [];
    var tmpMap = {};
    for (var i = 0, l = treeArray.length; i < l; i++) {
      // 以每条数据的id作为obj的key值，数据作为value值存入到一个临时对象里面
      tmpMap[treeArray[i]["id"]] = treeArray[i];
    }
    for (i = 0, l = treeArray.length; i < l; i++) {
      var key = tmpMap[treeArray[i]["pid"]];
      // console.log('key', key)
      //循环每一条数据的pid，假如这个临时对象有这个key值，就代表这个key对应的数据有children，需要Push进去
      //如果这一项数据属于哪个数据的子级
      if (key) {
        // 如果这个数据没有children
        if (!key["child"]) {
          key["child"] = [];
          key["child"].push(treeArray[i]);
          // 如果这个数据有children
        } else {
          key["child"].push(treeArray[i]);
        }
      } else {
        //如果没有这个Key值，就代表找不到属于哪个数据，那就代表没有父级,直接放在最外层
        r.push(treeArray[i]);
      }
    }
    return r
  }

})
